//
//  YCFillApplyInfoViewController.m
//  YCSchool
//
//  Created by Yanglixia on 16/5/1.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  填写报名信息

#import "YCFillApplyInfoViewController.h"
#import "YCEntryFeePayViewController.h"
#import "MultipleImagePickerViewController.h"
#import "LXActionSheet.h"
#import "YCFillApplyInfoCell.h"
#import "YCFillApplyModel.h"

@interface YCFillApplyInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate,YCFillApplyInfoCellDelegate>


/** scrollView */
@property (nonatomic, strong) UIScrollView *scrollView;
/** containerView */
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *footerView;

@property (nonatomic, strong) NSMutableArray *photoMutableArray;// 选中照片数组

@property (nonatomic, strong) UIButton *commitSignUpButton;// 提交报名按钮

/** 数组  */
@property (nonatomic, strong) NSMutableArray *applyInfoArray;

@property (nonatomic, strong) UIButton *addPhotoButton;// 添加相片按钮

@property (nonatomic , assign) CGRect firstResponseViewFrameOfWindow;// 相对于window的rect与键盘差值
/** 填写资料的模型  */
@property (nonatomic, strong) YCFillInfomationModel *fillInfoModel;
@end

@implementation YCFillApplyInfoViewController

- (NSMutableArray *)applyInfoArray
{
    if (!_applyInfoArray)
    {
        _applyInfoArray = [[NSMutableArray alloc] init];
        
        YCFillApplyModel *model = [[YCFillApplyModel alloc] init];
        model.send = NO;
        model.numberKeyBoard = NO;
        model.name = @"姓名";
        model.placeholder = @"请输入您的姓名";
        
        YCFillApplyModel *model1 = [[YCFillApplyModel alloc] init];
        model1.send = NO;
        model1.numberKeyBoard = NO;//身份证也有x字母存在
        model1.name = @"身份证号码";
        model1.placeholder = @"请输入您的身份证号码";
        
        YCFillApplyModel *model2 = [[YCFillApplyModel alloc] init];
        model2.send = NO;
        model2.numberKeyBoard = YES;
        model2.name = @"手机号码";
        model2.placeholder = @"请输入您的手机号码";
        
        YCFillApplyModel *model3 = [[YCFillApplyModel alloc] init];
        model3.send = YES;
        model3.numberKeyBoard = YES;
        model3.name = @"短信验证码";
        model3.placeholder = @"请输入4位验证码";
        
        YCFillApplyModel *model4 = [[YCFillApplyModel alloc] init];
        model4.send = NO;
        model4.numberKeyBoard = NO;
        model4.name = @"取件地址";
        model4.placeholder = @"请输入您的取件地址";
        
        [_applyInfoArray addObjectsFromArray:@[model,model1,model2,model3,model4]];
    }
    return _applyInfoArray;

}



- (NSMutableArray *)photoMutableArray
{
    if (!_photoMutableArray)
    {
        _photoMutableArray = [[NSMutableArray alloc] init];
    }
    return _photoMutableArray;
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}


- (UIView *)footerView
{
    if(!_footerView)
    {
        _footerView = [[UIView alloc] init];
        // 顶部分隔
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor yc_colorWithUInt:0xf7f7f7];
        [_footerView addSubview:line];
        
        // 提交身份证正面照label
        UILabel *commitIdCardLabel = [[UILabel alloc] init];
        commitIdCardLabel.text = @"提交身份证正面照";
        commitIdCardLabel.textColor = [UIColor yc_colorWithUInt:0x8c8c8c];
        commitIdCardLabel.font = [UIFont systemFontOfSize:14];
        [_footerView addSubview:commitIdCardLabel];
        
        UIButton *addPhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [addPhotoButton setImage:[UIImage imageNamed:@"添加照片"] forState:UIControlStateNormal];
        addPhotoButton.backgroundColor = [UIColor yc_colorWithUInt:0xb0b0b0];
        [addPhotoButton addTarget:self action:@selector(didTouchUpInsideSelectedIDCardImageButton:) forControlEvents:UIControlEventTouchUpInside];
        [_footerView addSubview:addPhotoButton];
        self.addPhotoButton = addPhotoButton;
        
        UIImageView *sampleImageView = [[UIImageView alloc] init];
        sampleImageView.image = [UIImage imageNamed:@"手持身份证"];//80*80样图

        [_footerView addSubview:sampleImageView];
        
        UILabel *introductionLabel = [[UILabel alloc] init];
        introductionLabel.numberOfLines = 0;
        [_footerView addSubview:introductionLabel];
        // 身份证上传说明
        NSString *text = @"身份证上的所有信息清晰可见,必须能看清证件号。\n照片需免冠，建议未化妆，手持证件人的五官清晰可见。\n照片内容真实有效，不得做任何修改。\n支持.jpg,bmp,.git格式照片，大小不超过5M。";
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
        style.lineSpacing=7;//行距
        style.alignment=NSTextAlignmentLeft;
        NSAttributedString *textValue = [[NSAttributedString alloc]initWithString:text attributes:@{NSParagraphStyleAttributeName:style,NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:[UIColor yc_colorWithUInt:0x808080]}];
        introductionLabel.attributedText= textValue;
        
        [_footerView addSubview:self.commitSignUpButton];
        
        // 添加备注
        UILabel *markLabel = [[UILabel alloc] init];
        NSString *string = @"注. 审核时间通常为3个工作日内";
        NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:[UIColor yc_colorWithUInt:0x808080]}];
        // 通过富文本设置注.颜色与大小
        [attrText addAttributes:@{NSForegroundColorAttributeName:[UIColor yc_colorWithUInt:0x00b4ff],NSFontAttributeName:[UIFont systemFontOfSize:12]} range:[string rangeOfString:@"注."]];
        markLabel.attributedText = attrText;
        [_footerView addSubview:markLabel];
        
        // 布局
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(_footerView);
            make.height.equalTo(@13);
        }];
        
        [commitIdCardLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_footerView).offset(15);
            make.top.equalTo(line.mas_bottom).offset(16);
        }];
        
        CGFloat margin = (kScreenWidth - 160 - 14) / 2.0;
        [addPhotoButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(commitIdCardLabel.mas_bottom).offset(26);
            make.left.equalTo(_footerView).offset(margin);
            make.width.height.equalTo(@80); //图片大小为80 * 80(160px * 160px)
        }];
        
        [sampleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(addPhotoButton);
            make.left.equalTo(addPhotoButton.mas_right).offset(14);
            make.width.height.equalTo(addPhotoButton); //图片大小为80 * 80(160px * 160px)
        }];
        
        [introductionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(addPhotoButton.mas_bottom).offset(26);
            make.left.equalTo(_footerView).offset(18);
            make.right.equalTo(_footerView).offset(-18);
        }];
        
        [self.commitSignUpButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_footerView).offset(50);
            make.right.equalTo(_footerView).offset(-50);
            make.height.equalTo(@35);
            make.centerX.equalTo(_footerView);
            make.top.equalTo(introductionLabel.mas_bottom).offset(heightFromIphone6Height(60));
        }];
        [markLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_footerView);
            make.top.equalTo(self.commitSignUpButton.mas_bottom).offset(25);
        }];
        
        [_footerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(kScreenWidth));
            make.bottom.equalTo(markLabel.mas_bottom).offset(40);//16
        }];
    }
    return _footerView;
}

- (UIButton *)commitSignUpButton
{
    if (!_commitSignUpButton) {
        _commitSignUpButton = [[UIButton alloc] init];
        _commitSignUpButton.backgroundColor = [UIColor yc_colorWithUInt:0x5270a7];
        _commitSignUpButton.layer.cornerRadius = 35 / 2;
        _commitSignUpButton.layer.masksToBounds = YES;
        [_commitSignUpButton setTitle:@"提交报名" forState:UIControlStateNormal];
        _commitSignUpButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_commitSignUpButton addTarget:self action:@selector(didTouchUpInsideCommitButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commitSignUpButton;
}


- (void)makeView
{
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.delegate = self;
    self.scrollView.backgroundColor = [UIColor whiteColor];
    // 添加单击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScrollView:)];
    [self.scrollView addGestureRecognizer:tap];
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    UIView *containerView = [[UIView alloc] init];
    containerView.backgroundColor = [UIColor whiteColor];
    self.containerView = containerView;
    [self.scrollView addSubview:containerView];
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [self.containerView addSubview:self.tableView];
    [self.containerView addSubview:self.footerView];

    CGFloat tableViewH = 4*heightFromIphone6Height(48) + heightFromIphone6Height(89);
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.containerView);
        make.height.equalTo(@(tableViewH));
    }];
    
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.right.equalTo(self.containerView);
    }];
    [self.containerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.footerView.mas_bottom);
    }];
    [self.scrollView layoutIfNeeded];
    self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.footerView.frame));
}

#pragma mark - 生命周期

- (id)initWithFillInfoModel:(YCFillInfomationModel *)model
{
    if (self = [super init]) {
        _fillInfoModel = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self yc_addBackBarButtonItem];
    self.navigationItem.title = @"填写报名信息";
    [self makeView];
    
    // 监听键盘弹出与关闭
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.applyInfoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YCFillApplyInfoCell *cell = [YCFillApplyInfoCell tabelViewWithTableView:tableView withIndexPath:indexPath];
                                 
    cell.delegate = self;
    cell.model = self.applyInfoArray[indexPath.row];
    return cell;
}

#pragma mark - UITableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == (self.applyInfoArray.count - 1)) {
        return heightFromIphone6Height(89);
    }
    return heightFromIphone6Height(48);
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollView) {
        
//        [self.view endEditing:YES];
    }
    YCLogFunc
}

#pragma mark - UIImagePickerController
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if(!image)
    {
        //
        [picker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    self.navigationItem.rightBarButtonItem.enabled = YES;
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击响应方法

- (void)tapScrollView:(UITapGestureRecognizer *)tap
{
    YCLogFunc
    [self.view endEditing:YES];
}

/// 提交报名
- (void)didTouchUpInsideCommitButton:(UIButton *)button
{
    if (![self checkIsValid]) {
        return;
    }
    YCLog(@"提交报名按钮被点击了...");
    [SVProgressHUD showWithStatus:@"提交报名中..."];
    NSDictionary *params = @{
                             @"uid":@"1",
                             @"token":accessToken_Test,
                             @"cartypeid":@(self.fillInfoModel.cartypeid),//选择的车型
                             @"classtypeid":@(self.fillInfoModel.cartypeid),//选择的班型
                             @"periodid":@(self.fillInfoModel.periodid),//选择的时段
                             @"spaceid":@(self.fillInfoModel.spaceid),//选择的场地
                             @"ycname":self.fillInfoModel.ycname,//填写的姓名
                             @"ycidcard":self.fillInfoModel.ycidcard,//身份证号
                             @"ycmobile":self.fillInfoModel.ycmobile,//手机号
                             @"ycaddress":self.fillInfoModel.ycaddress,//取件地址
                             @"ycidcardimg":self.fillInfoModel.ycidcardimg,//身份证图片
//                             @"ycpaytype":@"1",//支付方式 放至下一个接口中
                             };
    [[YCNetworManager shareManager] postWithUrl:YCAPIInfoInsert params:params success:^(NSURLSessionDataTask *task, ServiceResponse *response) {
        YCLog(@"%@",response.data);
        [SVProgressHUD dismiss];
        YCEntryFeePayViewController *entryPayVc = [[YCEntryFeePayViewController alloc] initWithFillInfoModel:self.fillInfoModel];
        [self.navigationController pushViewController:entryPayVc animated:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        YCLog(@"%@",error.localizedDescription);
        [SVProgressHUD dismiss];
        [self showMsg:@"报名失败,请重试"];
    }];
    
    YCEntryFeePayViewController *entryPayVc = [[YCEntryFeePayViewController alloc] initWithFillInfoModel:self.fillInfoModel];
    [self.navigationController pushViewController:entryPayVc animated:YES];
}

- (void)didTouchUpInsideSelectedIDCardImageButton:(UIButton *)button
{
    YCLogFunc
    [self.view endEditing:YES];
    LXActionSheet *sheet = [[LXActionSheet alloc] initWithCancelButtonTitle:@"取消" otherButtonTitlesArray:@[@"从手机相册选择",@"拍照"]];
    
    [sheet showInView:self.navigationController.view mask:YES maskColor:[UIColor darkGrayColor] click:^(NSUInteger index, LXActionSheet *sheet) {
        
        switch (index) {
            case 1:
            {
                YCLog(@"从手机相册中选择...");
                [MultipleImagePickerViewController presentMutipleImagePickerControllerAtViewController:self maxNumberOfImages:1 completion:^(NSArray *images) {
                    for (NSDictionary *obj in images)
                    {
                        UIImage *image = obj[MutipleOriginImageKey];
                        
                        [self.addPhotoButton setImage:image forState:UIControlStateNormal];
                        
                        // 身份证图片
                        self.fillInfoModel.ycidcardimg = [NSString yc_stringWithBase64FromUIImage:image];
//                        UIImage *newDecodeImage = [UIImage yc_imageFromBase64Str:self.fillInfoModel.ycidcardimg];//可以解出来
                    }
                    self.navigationItem.rightBarButtonItem.enabled = YES;
                    
                } cancel:nil];
            }
                break;
            case 2:
            {
                YCLog(@"拍照...");
                
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePicker.delegate = self;
                imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                [self presentViewController:imagePicker animated:YES completion:nil];
                
            }
                break;
                
            default:
                break;
        }
    } cancel:nil];

}

#pragma mark - 键盘弹出与关闭处理


- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 获取当前第一响应view
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIView *firstResponseView = [keyWindow performSelector:@selector(firstResponder)];
    _firstResponseViewFrameOfWindow = [firstResponseView convertRect:firstResponseView.bounds toView:keyWindow];
    
    if(rect.origin.y < kScreenHeight)//键盘上弹了
    {
        CGFloat offset = CGRectGetMaxY(_firstResponseViewFrameOfWindow) - CGRectGetMinY(rect)+15;//高出15
        if(offset < 0 ) return;
        rect = self.view.bounds;
        rect.origin.y = (offset);
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = rect;
        }];
    }
    else
    {
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        }];
    }
}

#pragma makr - FillApplyInfoCellDelegate
- (void)fillApplyInfoCellEndEdit:(YCFillApplyInfoCell *)cell
{
    for (YCFillApplyModel *model1 in self.applyInfoArray) {
        if ([model1.name isEqualToString:cell.model.name]) {
            model1.contentText = cell.model.contentText;//再次重新赋值，解决bug
        }
    }
}

#pragma mark - 验证

-(BOOL)checkIsValid
{

    NSInteger count = self.applyInfoArray.count;
    for (NSInteger i=0; i<count; i++) {
        YCFillApplyModel *model = self.applyInfoArray[i];
        NSString *newString = [model.contentText stringByReplacingOccurrencesOfString:@" " withString:@""];//去除空格
        switch (i) {
            case 0://姓名
            {
                self.fillInfoModel.ycname = newString;
            }
            break;
                
            case 1://身份证
            {
                self.fillInfoModel.ycidcard = newString;
            }
            break;
                
            case 2://手机号
            {
                self.fillInfoModel.ycmobile = newString;
            }
            break;
                
            case 3://短信验证
            {
//                self.fillInfoModel. = newString;
            }
            break;
                
            case 4://取件地址
            {
                self.fillInfoModel.ycaddress = newString;
            }
            break;
                
            default:
                break;
        }
    }
    if (self.fillInfoModel.ycname.length == 0   ||
        self.fillInfoModel.ycidcard.length == 0 ||
        self.fillInfoModel.ycmobile.length == 0 ||
        self.fillInfoModel.ycaddress.length == 0)
    
    {
        [self showMsg:@"每个选项都需要填写，不能为空"];
        return NO;
    }
    
    
    
    if (![self validateIdentityCard:self.fillInfoModel.ycidcard]) {
        [self showMsg:@"请填写有效的身份证号码"];
        return  NO;
    }
    
    if (![self validateMobile:self.fillInfoModel.ycmobile]) {
        [self showMsg:@"请填写有效的手机号码"];
        return NO;
    }
    
    if (self.fillInfoModel.ycidcardimg == nil) {
        [self showMsg:@"请选择一张身份证正面照"];
        return NO;
    }
    
    return YES;
}

//手机号码验证
- (BOOL)validateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

//身份证号
- (BOOL)validateIdentityCard:(NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}


-(void)showMsg:(NSString *)msg
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
    [alertView show];
}


@end
